//=================================================
// X_NC_serial.c
// 2015-03-28
//=================================================
#include <stdlib.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <termios.h>
//#include <sys/socket.h>
//#include <arpa/inet.h>
//#include <netdb.h>


#define BAUDRATE B9600   
// Arduino Control Protocol
#define ON_DELAY_VAL     2
#define ON_DELAY_UNIT    3
#define ON_STEPPER_DIR   4
#define ON_STEPPER_STEPS 5
#define ON_STEPPER_SPEED 6

#define MAX_RRNO  9

int nb_sid, nb_mid, nb_checksum;

struct termios tio;
int  tty_fd, flags;
int silent = 0;

// Global variables
char g_dev[80];
int g_rrno = 0; // round robin message id 0 - MAX_RRNO; 
unsigned char g_data_up[500];
//===============================
void delay(int t)
//===============================
{
  t = t*1000; // convert to ms
  usleep(t);
} 

//=================================================
void serialFlush()
//=================================================
{
  char c;
  if(silent==0)printf("\nGWY: flushing:");
  while(read(tty_fd,&c,1)>0) {
   if(silent==0)printf("(%c)",c);
  }
  if(silent==0)printf(":flushed\n");
}  

//===============================
void readDeviceName()
//===============================
{
  FILE  *in,*out;
  int n = 0;
  char  line[128];
  char  temps[12];

  system("ls /dev | grep ACM > device.nab"); 
  in = fopen("device.nab","r");
  if(in == NULL)
    {
      printf("No ACM device information file\n");
    }
  else
    {
      while (fgets(line,sizeof line,in) != NULL)
	{ 
          n++;
	  if(strstr(line,"ttyACM") != NULL)sscanf(line,"%s",temps);
	  strcpy(g_dev,"/dev/");
	  strcat(g_dev,temps);
	}
      fclose(in);
    }

  if(n > 1)printf("Multiple ACM devices found - check Arduino connection\n");

  if(n == 0)
  {
  system("ls /dev | grep USB > device.nab"); 
  in = fopen("device.nab","r");
  if(in == NULL)
    {
      printf("No USB device information file\n");
    }
  else
    {
      while (fgets(line,sizeof line,in) != NULL)
	{ 
      n++;
	  if(strstr(line,"ttyUSB") != NULL)sscanf(line,"%s",temps);
	  strcpy(g_dev,"/dev/");
	  strcat(g_dev,temps);
	}
      fclose(in);
    }

  if(n > 1)printf("Multiple USB devices found - check Arduino connection\n");
  }
  if(n == 0)
  {
	  printf("No device found - check Arduino connection\n");
	  exit(0);
  }
}
//===============================
void readIpAddress(char *ips)
//===============================
{
  FILE  *in;
  char  line[128];
  char  temps[12];
  int   net = 0,netType=0;

  system("ifconfig > ipaddress.nab");
  delay(1000);
  in = fopen("ipaddress.nab","r");
  if(silent==0)printf("Open ip file\n");
  strcpy(ips,"no ip found");
  while (fgets(line,sizeof line,in) != NULL)
  { 
          if(strstr(line,"wlan") != NULL)
          {
             net = 1; //wlan
          }
          if(strstr(line,"eth") != NULL)
          {
             net = 2; //eth
          }
          if(strstr(line,"Loopback") != NULL)
          {
             net = 3; //lo
          }
          if(strstr(line,"inet addr:") != NULL)
          {
             if(net != 3)
             {
               netType = net;
               sscanf(line,"%s %s",temps,ips);
             }
          }
  }
  fclose(in);
  if(silent==0)printf("%d %s\n",netType,ips);
  return;
}
//===============================
void releaseToken(char* com)
//===============================
{
  FILE  *out;
  printf("release %s\n",com);
  out = fopen(com,"w");
  fprintf(out,"1");
  fclose(out);
}
//===============================
int waitToken(char* com)
//===============================
{
  FILE  *in;
  char  line[128];
  int token = 0,timeout=0;
  printf("check %s...\n",com);
  while(token != 1 && timeout < 10)
  {
	timeout++;

    in = fopen(com,"r");
    if(in == NULL)
    {
      printf("No %s\n",com);
      releaseToken(com);
      return;
    }
    while(fgets(line,sizeof line,in) != NULL)
    { 
     sscanf(line,"%d",&token);
    }
    fclose(in);
    printf("%d %d\n",timeout,token);
    delay(1000);
  }
  printf("%s is free\n",com);
  return(token);
}
//===============================
void holdToken(char* com)
//===============================
{
  FILE  *out;
  printf("hold %s\n",com);
  out = fopen(com,"w");
  fprintf(out,"2");
  fclose(out);
}

//===============================
void writeUpLinkMsg(int rrno)
//===============================
{
  FILE  *out;
  char fname[80];
  if(silent==0)printf("Uplink Msg = %d\n",rrno);
  sprintf(fname,"uplink_msg_%d.nbc",rrno);
  out = fopen(fname,"w");
  fprintf(out,"%s",g_data_up);
  fclose(out);
}
//===============================
int processAllDownlinkMsg()
//===============================
{
  FILE  *in;
  int count = 0;
  char fname[80];
  char  line[128];
  
  sprintf(fname,"dl_msg_list.nbc");
  system("ls downlink_msg_*.nbc > dl_msg_list.nbc");
  //if(silent == 0)system("more dl_msg_list.nbc");
  
  in = fopen(fname,"r");
  if(in == NULL)
  {
      printf("No %s\n",fname);
      return(0);
  }
  while(fgets(line,sizeof line,in) != NULL)
  { 
	 count++;
     printf("%s",line);
  }
  fclose(in);
  return(count);
}
//===============================
void sendSerial()
//===============================
{
 printf("sendSerial\n");
}
//===============================
int recSerial()
//===============================
{
  unsigned char c='D';
  unsigned char z='D';
  int i,temp1,temp2,checksum;
 
  int nn = 0;
  while (c != ';')
    {
      if (read(tty_fd,&c,1)>0) 
        {
          //if(silent==0)printf("<%c>",c);
          g_data_up[nn] = c;
          nn++;
        }
    }
  c = ' ';
  g_data_up[nn-1] = '\0';
  
  if(silent==0)printf("Received from serial device: (%s) len=%d\n",g_data_up,nn);
  //nb_mid = 0;
  //sscanf(inres,"%d %d %d",&nb_mid,&nb_sid,&checksum);
 
  return(1);
}
//===============================
void init()
//===============================
{
  char ip[80];
  int i;
  
 
  readIpAddress(ip);
  readDeviceName();

  printf(  "Device....: %s\n",g_dev);
  printf(  "IP........: %s\n",ip);

 
  //printf("ARDUINO CONNECTION\n");
  memset(&tio,0,sizeof(tio));
  tio.c_iflag=0;
  tio.c_oflag=0;
  tio.c_cflag=CS8|CREAD|CLOCAL;  // 8n1, see termios.h for more information
  tio.c_lflag=0;
  tio.c_cc[VMIN]=1;
  tio.c_cc[VTIME]=5;
  if((tty_fd = open(g_dev , O_RDWR | O_NONBLOCK)) == -1)
  {
        if(silent==0)printf("GWY: Waiting for Arduino connection...\n"); 
  }
  else
  {
        printf("Connected to %s\n",g_dev); 
        cfsetospeed(&tio,BAUDRATE);    
        cfsetispeed(&tio,BAUDRATE);      
        tcsetattr(tty_fd,TCSANOW,&tio);
        tcsetattr(tty_fd, TCSAFLUSH, &tio);
  }            
      
  //for(i=0;i<100;i++)on[i] = 0;
  delay(1000);
  //g_count = 0;
  //writeDebug();
  //if(silent==0)printf("GWY: Arduino sync ...\n"); 
  //syncArduino();
  //if(silent==0)printf("GWY:Arduino sync ok\n"); 
}
//===============================
int main(int argc, char **argv)
//===============================
{   
  int i,value = 9999, nc_state;
  time_t tm;
  struct tm *ltime;
  int go = 0,tok = 0;

  char res[120],stemp[120],sys[240];
      
  if(argc == 2)
  {
    if(strstr(argv[1],"-d") != NULL) 
     silent = 0;
  }
  
 
  init(); 
  while(1)
  {
	  // Check if any data from serial device
      go = 0;
      go = recSerial();
      
      // Put msg, if any, in uplink mailbox
      if(go == 1)
      {
		  g_rrno++;
		  if(g_rrno > MAX_RRNO) g_rrno = 0;
		  writeUpLinkMsg(g_rrno);
      }
 
 	  // Check if any data from http 

      processAllDownlinkMsg();
      delay(500);
  }
           
  close(tty_fd);
  return EXIT_SUCCESS;
}
